/*
 *
 *  * | Licensed 未经许可不能去掉「OPENIITA」相关版权
 *  * +----------------------------------------------------------------------
 *  * | Author: xw2sy@163.com
 *  * +----------------------------------------------------------------------
 *
 *  Copyright [2024] [OPENIITA]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * /
 */

package cc.iotkit.data.service;

import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.constant.UserConstants;
import cc.iotkit.common.utils.MapstructUtils;
import cc.iotkit.common.utils.StringUtils;
import cc.iotkit.data.dao.IJPACommData;
import cc.iotkit.data.dao.SysTenantRepository;
import cc.iotkit.data.model.TbSysDept;
import cc.iotkit.data.model.TbSysTenant;
import cc.iotkit.data.system.ISysTenantData;
import cc.iotkit.data.util.PredicateBuilder;
import cc.iotkit.model.system.SysDept;
import cc.iotkit.model.system.SysTenant;
import cc.iotkit.model.system.SysUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

import static cc.iotkit.data.model.QTbBasArea.tbBasArea;
import static cc.iotkit.data.model.QTbSysDept.tbSysDept;
import static cc.iotkit.data.model.QTbSysRole.tbSysRole;
import static cc.iotkit.data.model.QTbSysTenant.tbSysTenant;
import static cc.iotkit.data.model.QTbSysUser.tbSysUser;
import static cc.iotkit.data.model.QTbSysUserRole.tbSysUserRole;

/**
 * @Author：tfd
 * @Date：2023/5/31 9:45
 */
@Primary
@Service
@RequiredArgsConstructor
public class SysTenantDataImpl implements ISysTenantData, IJPACommData<SysTenant, Long> {
    @PersistenceContext
    private EntityManager entityManager;
    private final SysTenantRepository sysTenantRepository;

    private final JPAQueryFactory jpaQueryFactory;

    @Override
    public JpaRepository getBaseRepository() {
        return sysTenantRepository;
    }

    @Override
    public Class getJpaRepositoryClass() {
        return TbSysTenant.class;
    }

    @Override
    public Class getTClass() {
        return SysTenant.class;
    }


    @Override
    public List<SysTenant> findAllByCondition(SysTenant data) {
        List<SysTenant> ret=jpaQueryFactory.select(Projections.bean(SysTenant.class,tbSysTenant.id, tbSysTenant.createBy, tbSysTenant.createDept, tbSysTenant.createTime, tbSysTenant.updateBy, tbSysTenant.updateTime, tbSysTenant.accountCount, tbSysTenant.address, tbSysTenant.companyName, tbSysTenant.contactPhone, tbSysTenant.contactUserName, tbSysTenant.delFlag,
                                tbSysTenant.remark, tbSysTenant.status, tbSysTenant.tenantCode, tbSysTenant.areaId,tbBasArea.areaName))
                        .from(tbSysTenant).leftJoin(tbBasArea).on(tbSysTenant.areaId.eq(tbBasArea.id))
                        .where(PredicateBuilder.instance()
                .and(StringUtils.isNotBlank(data.getTenantCode()),()->tbSysTenant.tenantCode.eq(data.getTenantCode()))
                .and(StringUtils.isNotBlank(data.getContactUserName()),()->tbSysTenant.contactUserName.like(data.getContactUserName()))
                .and(StringUtils.isNotBlank(data.getContactPhone()),()->tbSysTenant.contactPhone.eq(data.getContactPhone()))
                .and(StringUtils.isNotBlank(data.getCompanyName()),()->tbSysTenant.companyName.like(data.getCompanyName()))
                .and(StringUtils.isNotBlank(data.getStatus()),()->tbSysTenant.status.eq(data.getStatus()))
                .build()).fetch();
        return ret;// MapstructUtils.convert(ret, SysTenant.class);
    }

    @Override
    public boolean checkCompanyNameUnique(SysTenant tenant) {
        final TbSysTenant ret = jpaQueryFactory.select(tbSysTenant).from(tbSysTenant)
                .where(PredicateBuilder.instance()
                        .and(tbSysTenant.companyName.eq(tenant.getCompanyName()))
                        .and(Objects.nonNull(tenant.getId()), () -> tbSysTenant.id.ne(tenant.getId()))
                        .build()).fetchOne();
        return Objects.isNull(ret);
    }

    public Paging<SysTenant> queryPageList(PageRequest<SysTenant> query) {
        SysTenant data=query.getData();
        PredicateBuilder builder = PredicateBuilder.instance();
        if (Objects.nonNull(data)) {
            builder.and(StringUtils.isNotBlank(data.getTenantCode()),()->tbSysTenant.tenantCode.eq(data.getTenantCode()))
                    .and(StringUtils.isNotBlank(data.getContactUserName()),()->tbSysTenant.contactUserName.like(data.getContactUserName()))
                    .and(StringUtils.isNotBlank(data.getContactPhone()),()->tbSysTenant.contactPhone.eq(data.getContactPhone()));
        }

        QueryResults<SysTenant> results = jpaQueryFactory.select(Projections.bean(SysTenant.class,
                        tbSysTenant.id, tbSysTenant.createBy, tbSysTenant.createDept, tbSysTenant.createTime, tbSysTenant.updateBy, tbSysTenant.updateTime, tbSysTenant.accountCount, tbSysTenant.address, tbSysTenant.companyName, tbSysTenant.contactPhone, tbSysTenant.contactUserName, tbSysTenant.delFlag,
                        tbSysTenant.remark, tbSysTenant.status, tbSysTenant.tenantCode, tbSysTenant.areaId,tbBasArea.areaName))
                .from(tbSysTenant).leftJoin(tbBasArea).on(tbSysTenant.areaId.eq(tbBasArea.id))
                .where(builder.build()).offset(query.getOffset()).limit(query.getPageSize()).fetchResults();
        return new Paging<>(results.getTotal(), results.getResults());

    }

    /**
     * 获取绑定产品的租户
     * @param productId
     * @return
     */
    public List<SysTenant> findByProductId(Long productId){
        String nativeQuery = "SELECT * FROM sys_tenant a\n" +
                "LEFT JOIN product b on JSON_CONTAINS(JSON_ARRAY(b.tenant_id),JSON_ARRAY(a.id))\n" +
                "where b.id=:productId ";
        List<SysTenant> result = entityManager
                .createNativeQuery(nativeQuery, TbSysTenant.class)
                .setParameter("productId", productId)
                .getResultList();
        return MapstructUtils.convert(result, SysTenant.class);
    }

}
